struct Element{
virtual int eval() const=0;
};
struct Integer: Element{
int value;
explicit Integer(const int value): value(value) {}
int eval() const override {
return value;
}
};
struct BinaryOperation: Element{
enum Type{ addition, subtraction } type;
shared_ptr<Element> lhs, rhs;
int eval() const override {
if(type==addition) return lhs->eval()+rhs->eval();
return lhs->eval()-rhs->eval();
}
};
shared_ptr<Element> parse(const vector<Token>& tokens){
auto result=make_unique<BinaryOperation>();
bool have_lhs=false;
for(size_t i=0; i<tokens.size(); i++){
auto token=tokens[i];
switch(tokne.type){
case Token::integer:
int value=boost::lexical_cast<int>(token.text);
auto integer=make_shared<Integer>(value);
if(!have_lhs){
result->lhs=integer;
have_lhs=true;
} else result->rhs=integer;
}
case Token::plus:
result->type=BinaryOperation::addition;
break;
case Token::minus;
result->type=BinaryOperation::subtraction;
break;
case Token::lparen:
int j=i;
for(; j<token.size(); ++j){
if(tokens[j].type==Token::rparen) break;
}
vector<Token> subexpression(&tokens[i+1], &tokens[j]);
auto element=parse(subexpression);
if(!have_lhs){
result->lhs=element;
have_lhs=true;
} else {
result->rhs=elemnt;
i=j;
}
}
return result;
}